<template>
  <div ref="chartRef" class="chart" :style="{ width: width, height: height }"></div>
</template>

<script>
import * as echarts from 'echarts'
import ElementResizeDetector from 'element-resize-detector'
export default {
  name: 'EChart',
  props: {
    option: {
      type: Object,
      required: true
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '360px'
    }
  },
  components: {},
  data() {
    return {
      chart: null,
      erd: null,
      timer: null
    }
  },
  computed: {},
  watch: {
    option: {
      handler(newVal) {
        this.chart.clear()
        this.chart.setOption(newVal)
        this.chart.setOption({ backgroundColor: 'rgba(255, 255, 255, 0)' })
      },
      deep: true
    },
    width: {
      handler() {
        this.chart.resize()
      }
    },
    height: {
      handler() {
        this.chart.resize()
      }
    }
  },
  methods: {},
  beforeCreate() { },
  created() { },
  beforeMount() { },
  mounted() {
    this.chart = echarts.init(this.$refs['chartRef'])
    this.erd = ElementResizeDetector({ strategy: 'scroll', callOnAdd: true })
    this.erd.listenTo(this.$refs['chartRef'], () => {
      if (this.timer !== null) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.chart.resize()
        if (this.timer !== null) {
          clearTimeout(this.timer)
          this.timer = null
        }
      }, 200)
    })
    this.chart.setOption(this.option)
    this.chart.setOption({ backgroundColor: 'rgba(255, 255, 255, 0)' })
  },
  beforeDestroy() {
    if (this.timer !== null) {
      clearTimeout(this.timer)
      this.timer = null
    }
    if (this.chart !== null) {
      this.chart.dispose()
      this.chart = null
    }
  },
  destroyed() { }
}
</script>